<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>promise</title>
</head>
<body>
	<h1>Promise测试</h1>
	<button id="btn-run">Run</button>
	<div id="msg"></div>

	<script type="text/javascript">
		document.querySelector("#btn-run")
			.onclick = function() {
				var msgObj = document.querySelector("#msg");
				msgObj.innerHTML = "";

				function appLog(msg) {
					msgObj.innerHTML = msgObj.innerHTML + "<p>" + msg + "</p>";
				}

				var p = new Promise(function(resolve, reject){
					var r = Math.floor(Math.random(1) * 100);
					console.log(r);
					setTimeout(function(arg){
						console.log("arg %d", arg);
						appLog("arg " + arg);
						if(r % 2 == 0) {
							resolve(arg);
						} else {
							reject(arg);
						}
					},1000,10);
				});
				p.then(function(result){
					console.log("result %d", result);
				}, function(error) {
					console.log("error %d", error);
				}).then(function(result){
					console.log("result2 " + result);
				});

				// p.then(function(result){
				// 	return new Promise(function(resolve, reject){
				// 		setTimeout(function(arg){
				// 			console.log("add: %d", result + result);
				// 			appLog("add: " + (result * result));
				// 			resolve(result + result)
				// 		}, 1000);
				// 	});
				// }).then(function(result){
				// 	return new Promise(function(resolve, reject){
				// 		setTimeout(function(arg){
				// 			console.log("multiple: %d", result * result);
				// 			appLog("multiple: " + (result * result));
				// 			resolve(result * result)
				// 		}, 1000);
				// 	});
				// }).then(function(result){
				// 	return new Promise(function(resolve, reject){
				// 		setTimeout(function(arg){
				// 			console.log("sub: %d", result - result);
				// 			appLog("sub: " + (result - 10));
				// 			resolve(result - result)
				// 		}, 1000);
				// 	});
				// }).then(function(result){
				// 	console.log("reuslt: %d", result);
				// 	appLog("reuslt: " + result);
				// })
				
			}

			var callbacks = [
				function(arg) {
					console.log("first callback arg: %o", arg);
				},
				function(arg) {
					console.log("second callback arg: %o", arg);
				}
			];

			var resolves = [];
			var rejects = [];

			var promises = callbacks.map(function(_,i){
				return new Promise(function(resolve,reject) {
					resolves[i] = resolve;
					rejects[i] = reject;
				});
			});
			// promises[0].then(function(result) {
			// 	console.log("result: %s", result);
			// });
			// Promise.resolve(callbacks[0]('test')).then(function() {
			// 	resolves[0]("test");
			// })
			// console.log(promises);
			var arg = { value: "promise test" };
			callbacks.forEach(function(callback,i){
				Promise.resolve(callback(arg)).then(function() {
					console.log("resolves %d", i);
					resolves[i](arg);
					console.log("resolves %d", i);
				});
			});

	</script>
</body>
</html>